package com.zte.claa.inficombo.csa.app.service.dataredeal.impl;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.zte.claa.inficombo.csa.app.model.redis.DevMeteData;
import com.zte.claa.inficombo.csa.app.service.dataredeal.IMetedataRedealer;
import com.zte.claa.inficombo.csa.app.service.dataredeal.MetedataRedealService;
import com.zte.claa.inficombo.csa.app.service.redis.CSAMessagePublisher;

@Service
public class MetedataRedealServiceImpl implements MetedataRedealService {
	// 日志
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	// 消息发布器
	private CSAMessagePublisher msgPublisher = null;	
	
	// 需要二次处理的devtypeid和redealer映射表.
	private Map<String, IMetedataRedealer> redealerMap = new ConcurrentHashMap<String, IMetedataRedealer>();

	// 注册IMetedataRedealer
	public void registMetedataRedealer(String devtypeId, IMetedataRedealer redealer) {
		this.redealerMap.put(devtypeId, redealer);	
		redealer.setCSAMessagePublisher(this.msgPublisher);
	}

	// 配置消息发布器.
	@Override 
	public void setCSAMessagePublisher(CSAMessagePublisher publisher) {
		this.msgPublisher = publisher;
		Iterator<String> it = this.redealerMap.keySet().iterator();
		while(it.hasNext()){
			String devTpId = it.next();
			IMetedataRedealer redealer = this.redealerMap.get(devTpId);
			if(redealer != null){
				redealer.setCSAMessagePublisher(publisher);
			}
		}
	}
	
	// 判断是否需要二次处理.
	@Override
	public boolean needRedeal(String devtypeId) {
		return (this.redealerMap.get(devtypeId) != null);
	}

	// 提交metedata数据.
	@Override
	public void submitMetedata(DevMeteData data) {
		String devtypeId = data.getDevtype();
		IMetedataRedealer redealer = this.redealerMap.get(devtypeId);
		if(redealer != null){
			redealer.submitMetedata(data);
		} else {
			logger.warn("IMetedataRedealer not exist for devtype: {}", devtypeId);
		}
	}
	
	// 提交一批待合并数据（前提是需要合并）
	public void submitMetedatas(String devtypeId, List<DevMeteData> dataList) {
		if(dataList == null || dataList.size() == 0){
			return;
		}
		IMetedataRedealer redealer = this.redealerMap.get(devtypeId);
		if(redealer != null){
			redealer.submitMetedatas(dataList);
		} else {
			logger.warn("IMetedataRedealer not exist for devtype: {}", devtypeId);
		}
	}
	
}
